<template>
  <div class="max-w-6xl mx-auto">
    <!-- 标题和时间范围选择 -->
    <div class="flex items-center justify-between mb-6">
      <h1 class="text-2xl font-bold">学习进度</h1>
      <div class="flex items-center space-x-4">
        <div class="flex bg-gray-100 rounded-lg p-1">
          <button
            v-for="range in timeRanges"
            :key="range.value"
            @click="selectedTimeRange = range.value"
            :class="`px-3 py-1 rounded-md text-sm font-medium transition-colors ${
              selectedTimeRange === range.value
                ? 'bg-white text-blue-600 shadow-sm'
                : 'text-gray-600 hover:text-blue-600'
            }`"
          >
            {{ range.label }}
          </button>
        </div>
        <button
          @click="handleRefresh"
          :disabled="refreshing"
          class="flex items-center px-3 py-2 text-sm font-medium text-gray-600 hover:text-blue-600 transition-colors"
        >
          <RefreshCw :class="`h-4 w-4 mr-1 ${refreshing ? 'animate-spin' : ''}`" />
          刷新
        </button>
      </div>
    </div>
    
    <!-- 统计卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-8">
      <div 
        v-for="(stat, index) in stats"
        :key="stat.id"
        class="bg-white rounded-xl shadow-sm p-5"
        :style="{
          opacity: loading ? 0.5 : 1,
          transform: loading ? 'translateY(10px)' : 'none',
          transition: 'opacity 0.3s, transform 0.3s',
          transitionDelay: `${0.1 * (index + 1)}s`
        }"
      >
        <div :class="`w-12 h-12 rounded-full ${stat.bgColor} flex items-center justify-center mb-3`">
          <component :is="stat.icon" class="h-6 w-6" :class="stat.iconColor" />
        </div>
        <h3 class="text-2xl font-bold text-gray-900">{{ stat.value }}</h3>
        <p class="text-gray-500 text-sm">{{ stat.label }}</p>
        <div class="mt-2 flex items-center text-xs" :class="stat.trendColor">
          <component :is="stat.trendIcon" class="h-3 w-3 mr-1" />
          <span>{{ stat.trendText }}</span>
        </div>
      </div>
    </div>

    <!-- 本周目标 -->
    <div 
      class="bg-white rounded-xl shadow-sm p-6 mb-8"
      :style="{
        opacity: loading ? 0.5 : 1,
        transform: loading ? 'translateY(10px)' : 'none',
        transition: 'opacity 0.3s, transform 0.3s',
        transitionDelay: '0.5s'
      }"
    >
      <h2 class="text-xl font-bold mb-4">本周学习目标</h2>
      <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
        <div 
          v-for="goal in weeklyGoals"
          :key="goal.id"
          class="space-y-3"
        >
          <div class="flex items-center justify-between">
            <span class="text-sm font-medium text-gray-700">{{ goal.title }}</span>
            <span class="text-sm text-gray-500">
              {{ goal.current }}/{{ goal.target }} {{ goal.unit }}
            </span>
          </div>
          <div class="w-full bg-gray-200 rounded-full h-2">
            
            <div 
              class="h-2 rounded-full"
              
              :class="`${goal.color}`"
              :style="{ width: `${Math.min((goal.current / goal.target) * 100, 100)}%` }"
            ></div>
          </div>
          <div class="text-xs text-gray-500">
            还需 {{ Math.max(goal.target - goal.current, 0) }} {{ goal.unit }}
          </div>
        </div>
      </div>
    </div>

    <!-- 成就系统 -->
    <div 
      class="bg-white rounded-xl shadow-sm p-6 mb-8"
      :style="{
        opacity: loading ? 0.5 : 1,
        transform: loading ? 'translateY(10px)' : 'none',
        transition: 'opacity 0.3s, transform 0.3s',
        transitionDelay: '0.6s'
      }"
    >
      <h2 class="text-xl font-bold mb-4">学习成就</h2>
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <div
          v-for="achievement in achievements"
          :key="achievement.id"
          :class="`p-4 rounded-lg border-2 transition-all ${
            achievement.unlocked
              ? 'border-yellow-200 bg-yellow-50'
              : 'border-gray-200 bg-gray-50'
          }`"
        >
          <div class="flex flex-col items-center text-center">
            <div :class="`w-12 h-12 rounded-full flex items-center justify-center mb-3 ${
              achievement.unlocked ? 'bg-yellow-100' : 'bg-gray-200'
            }`">
              <component :is="achievement.icon" class="h-6 w-6" :class="achievement.iconColor" />
            </div>
            <h3 :class="`font-semibold ${achievement.unlocked ? 'text-gray-800' : 'text-gray-500'}`">
              {{ achievement.name }}
            </h3>
            <p :class="`text-xs mt-1 ${achievement.unlocked ? 'text-gray-600' : 'text-gray-500'}`">
              {{ achievement.description }}
            </p>
            <div v-if="!achievement.unlocked && achievement.progress !== undefined" class="mt-3 w-full">
              <div class="flex justify-between text-xs text-gray-500 mb-1">
                <span>进度</span>
                <span>{{ achievement.progress }}/{{ achievement.maxProgress }}</span>
              </div>
              <div class="w-full bg-gray-200 rounded-full h-1.5">
                <div 
                  class="bg-blue-500 h-1.5 rounded-full"
                  :style="{ width: `${(achievement.progress / achievement.maxProgress) * 100}%` }"
                ></div>
              </div>
            </div>
            <div v-if="achievement.unlocked" class="mt-2 flex items-center text-xs text-yellow-600">
              <Star class="h-3 w-3 mr-1 fill-current" />
              <span>已解锁</span>
            </div>
          </div>
        </div>
      </div>
    </div>

<!--     知识掌握度热力图
    <div 
      v-if="dashboardData?.knowledgeHeatmap"
      class="mb-8"
      :style="{
        opacity: loading ? 0.5 : 1,
        transform: loading ? 'translateY(10px)' : 'none',
        transition: 'opacity 0.3s, transform 0.3s',
        transitionDelay: '0.7s'
      }"
    >
      <KnowledgeHeatmap :data="dashboardData.knowledgeHeatmap" />
    </div> -->

<!--     学习进度图表
    <div
      :style="{
        opacity: loading ? 0.5 : 1,
        transform: loading ? 'translateY(10px)' : 'none',
        transition: 'opacity 0.3s, transform 0.3s',
        transitionDelay: '0.8s'
      }"
    >
      <LearningProgress 
        :userId="'current-user'"
        :data="{
          dates: dashboardData?.dates || [],
          correctRates: dashboardData?.correctRates || [],
          topics: dashboardData?.topics || []
        }"
      />
    </div>  -->

    <!-- 加载状态 -->
    <div v-if="loading" class="fixed inset-0 flex items-center justify-center bg-white bg-opacity-70 z-50">
      <div class="animate-spin rounded-full h-12 w-12 border-4 border-blue-500 border-t-transparent"></div>
    </div>

    <!-- 错误提示 -->
    <div v-if="error" class="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50 z-50">
      <div class="bg-white rounded-lg p-6 max-w-md mx-4">
        <h3 class="text-lg font-medium text-gray-900 mb-2">加载失败</h3>
        <p class="text-gray-600 mb-4">{{ error }}</p>
        <div class="flex justify-end space-x-3">
          <button 
            @click="error = null"
            class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50"
          >
            取消
          </button>
          <button 
            @click="fetchDashboardData"
            class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
          >
            重试
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { 
  Award, 
  Clock, 
  CheckCircle, 
  Calendar, 
  TrendingUp, 
  Target, 
  Brain, 
  Star, 
  RefreshCw 
} from 'lucide-vue-next';
import KnowledgeHeatmap from '../components/dashboard/KnowledgeHeatmap.vue';
import LearningProgress from '../components/dashboard/LearningProgress.vue';
// import { problemService } from '../services/apiService';
import {progressService} from '../services/apiService';


// 响应式数据
const dashboardData = ref(null);
const loading = ref(true);
const error = ref(null);
const selectedTimeRange = ref('week');
const refreshing = ref(false);

// 时间范围选项
const timeRanges = ref([
  { value: 'week', label: '本周' },
  { value: 'month', label: '本月' },
  { value: 'year', label: '本年' }
]);

// 统计卡片数据
const stats = ref([
  {
    id: '1',
    value: '0',
    label: '已解决题目',
    icon: CheckCircle,
    iconColor: 'text-green-500',
    bgColor: 'bg-green-100',
    trendIcon: TrendingUp,
    trendColor: 'text-green-600',
    trendText: '比上周 +0'
  },
  {
    id: '2',
    value: '0天',
    label: '当前连续学习',
    icon: Calendar,
    iconColor: 'text-blue-500',
    bgColor: 'bg-blue-100',
    trendIcon: Target,
    trendColor: 'text-blue-600',
    trendText: '目标: 0天'
  },
  {
    id: '3',
    value: '0分钟',
    label: '平均解题时间',
    icon: Clock,
    iconColor: 'text-purple-500',
    bgColor: 'bg-purple-100',
    trendIcon: TrendingUp,
    trendColor: 'text-purple-600',
    trendText: '效率提升 0%'
  },
  {
    id: '4',
    value: '初级',
    label: '当前等级',
    icon: Award,
    iconColor: 'text-yellow-500',
    bgColor: 'bg-yellow-100',
    trendIcon: null,
    trendColor: '',
    trendText: ''
  }
]);

// 每周目标
const weeklyGoals = ref([
  {
    id: '1',
    title: '解题数量',
    current: 0,
    target: 20,
    unit: '题',
    color: 'bg-blue-500'
  },
  {
    id: '2',
    title: '学习时长',
    current: 0,
    target: 300,
    unit: '分钟',
    color: 'bg-yellow-300'
  },
  {
    id: '3',
    title: '正确率',
    current: 0,
    target: 90,
    unit: '%',
    color: 'bg-green-500'
  }
]);

// 成就数据
const achievements = ref([
  {
    id: '1',
    name: '快速思考者',
    description: '5题内每题用时不超过2分钟',
    icon: Clock,
    iconColor: 'text-yellow-500',
    unlocked: false,
    progress: 0,
    maxProgress: 5
  },
  {
    id: '2',
    name: '数学爱好者',
    description: '完成5个不同类别的题目',
    icon: Brain,
    iconColor: 'text-blue-500',
    unlocked: false,
    progress: 0,
    maxProgress: 5
  },
  {
    id: '3',
    name: '持续学习者',
    description: '保持10天连续学习',
    icon: Calendar,
    iconColor: 'text-green-500',
    unlocked: false,
    progress: 0,
    maxProgress: 10
  },
  {
    id: '4',
    name: '数据大师',
    description: '正确解决10道统计题',
    icon: TrendingUp,
    iconColor: 'text-purple-500',
    unlocked: false,
    progress: 0,
    maxProgress: 10
  }
]);

// 获取仪表盘数据
const fetchDashboardData = async () => {
  try {
    loading.value = true;
    refreshing.value = true;
    error.value = null;
    
    const userId = 1;
    let response = await progressService.getDashboard(userId);
    let data=response.data;
    console.log(data);
    
    // const data={}
    
    
    // 更新数据
    dashboardData.value = {
      ...data,
      topics: [
        { name: "代数运算", mastery: 0.85 },
        { name: "几何证明", mastery: 0.72 },
        { name: "函数图像", mastery: 0.68 },
        { name: "概率统计", mastery: 0.55 },
        { name: "立体几何", mastery: 0.45 }
      ]
    };

    // 更新统计卡片
    stats.value[0].value = data.solvedNum || '0';
    stats.value[0].trendText = '比上周 +12';
    stats.value[1].value = data.continuousDay+" 天" || '0';
    stats.value[1].trendText = '目标: 10天';
    stats.value[2].value = data.averageTime/60+" 分钟" || '0';
    stats.value[2].trendText = '效率提升 5%';

    let levelStr="";
    switch(data.level){
      case "junior": levelStr="初级";break;
      case "medium": levelStr="中级";break;
      case "senior": levelStr="高级";break;
      default:;break;
    }


    stats.value[3].value = levelStr || '初级';

    response = await progressService.getLearnGoal(userId);
    data=response.data;
    console.log(data);
    

    
    // 更新每周目标
    weeklyGoals.value[0].current = data.solvedNum || 0;
    weeklyGoals.value[1].current = data.learnTime/60 ||99;
    weeklyGoals.value[2].current = data.accuracy ||99;


    weeklyGoals.value[0].target = data.goalSolvedNum || 99;
    weeklyGoals.value[1].target = data.goalLearnTime/60 ||99;
    weeklyGoals.value[2].target = data.goalAccuracy ||99;
    
    // 更新成就
    achievements.value[0].progress = 5;
    achievements.value[0].unlocked = true;
    achievements.value[1].progress = 5;
    achievements.value[1].unlocked = true;
    achievements.value[2].progress = 7;
    achievements.value[3].progress = 3;
    
  } catch (err) {
    console.error('Failed to fetch dashboard data:', err);
    error.value = err.message || '获取数据失败';
  } finally {
    loading.value = false;
    refreshing.value = false;
  }
};

// 刷新数据
const handleRefresh = () => {
  fetchDashboardData();
};

// 组件挂载时获取数据
onMounted(() => {
  fetchDashboardData();
});
</script>

<style scoped>
/* 自定义动画 */
.animate-spin {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
